package com.application.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.application.util.MySQLiteOpenHelper;

public class SQLiteDeleteViewModel extends AndroidViewModel {
    // 双向绑定的输入数据
    public final MutableLiveData<String> nameLiveData = new MutableLiveData<>("");
    public final MutableLiveData<String> numberLiveData = new MutableLiveData<>("");

    // 通知View的事件
    public final MutableLiveData<String> toastMsgEvent = new MutableLiveData<>(""); // Toast消息
    public final MutableLiveData<Boolean> clearInputEvent = new MutableLiveData<>(false); // 清空输入事件
    public final MutableLiveData<Boolean> showDialogEvent = new MutableLiveData<>(false); // 显示确认对话框事件

    private MySQLiteOpenHelper dbHelper;

    public SQLiteDeleteViewModel(@NonNull Application application) {
        super(application);
        dbHelper = new MySQLiteOpenHelper(application);
    }

    // 检查输入并准备删除（触发对话框）
    public void prepareDelete() {
        String name = nameLiveData.getValue();
        String number = numberLiveData.getValue();

        // 输入校验
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(number)) {
            toastMsgEvent.setValue("请输入姓名和学号");
            return;
        }

        // 触发显示确认对话框
        showDialogEvent.setValue(true);
    }

    // 执行删除操作（对话框确认后调用）
    public void performDelete() {
        String name = nameLiveData.getValue();
        String number = numberLiveData.getValue();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(number)) {
            return; // 双重校验，避免空值
        }

        // 调用数据库删除
        int row = dbHelper.deleteFromDbByNameAndNumber(name, number);
        if (row > 0) {
            toastMsgEvent.setValue("删除成功" + row + "条信息");
            clearInputEvent.setValue(true); // 通知清空输入
        } else {
            toastMsgEvent.setValue("未找到学生信息");
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
